<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Lottery;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\VerificationCode;
use App\Models\LotteryResult;

class LotteryController extends Controller
{
    /**
     * 显示摇奖活动列表
     */
    public function index(Request $request)
    {
        // 获取搜索关键词
        $keyword = $request->input('keyword');

        // 构建查询
        $query = \App\Models\WechatUser::select('id', 'openid', 'nickname', 'created_at');
        
        // 如果有搜索关键词，添加模糊查询条件
        if ($keyword) {
            $query->where('nickname', 'like', '%' . $keyword . '%');
        }

        // 获取微信用户数据，带分页
        $wechatUsers = $query->latest()->paginate(20);

        // 获取微信用户总数
        $totalUsers = \App\Models\WechatUser::count();
        
        // 获取当前搜索结果的数量
        $searchCount = $keyword ? $query->count() : $totalUsers;

        return view('lottery.index', compact('wechatUsers', 'totalUsers', 'keyword', 'searchCount'));
    }

    /**
     * 显示创建摇奖活动的表单
     */
    public function create()
    {
        return view('lottery.create');
    }

    /**
     * 保存新创建的摇奖活动
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
            'status' => 'required|in:0,1,2',
        ]);

        Lottery::create($validated);

        return redirect()
            ->route('admin.lottery.index')
            ->with('success', '摇奖活动创建成功！');
    }

    /**
     * 显示指定的摇奖活动
     */
    public function show(Lottery $lottery)
    {
        return view('lottery.show', compact('lottery'));
    }

    /**
     * 显示编辑摇奖活动的表单
     */
    public function edit(Lottery $lottery)
    {
        return view('lottery.create', compact('lottery'));
    }

    /**
     * 更新指定的摇奖活动
     */
    public function update(Request $request, Lottery $lottery)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
            'status' => 'required|in:0,1,2',
        ]);

        $lottery->update($validated);

        return redirect()
            ->route('admin.lottery.index')
            ->with('success', '摇奖活动更新成功！');
    }

    /**
     * 删除指定的摇奖活动
     */
    public function destroy(Lottery $lottery)
    {
        $lottery->delete();

        return response()->json([
            'success' => true,
            'message' => '摇奖活动删除成功！'
        ]);
    }

    /**
     * 执行抽奖
     */
    public function draw()
    {
        try {
            // 获取所有用户ID作为摇号池
            $userIds = \App\Models\WechatUser::pluck('id')->toArray();
            
            // 检查是否有用户参与
            if (empty($userIds)) {
                return response()->json([
                    'success' => false,
                    'message' => '没有可参与抽奖的用户！'
                ], 400);
            }

            // 随机抽取一个ID
            $winnerId = $userIds[array_rand($userIds)];
            
            // 获取中奖用户信息，添加 created_at 字段
            $winner = \App\Models\WechatUser::select('id', 'openid', 'nickname', 'created_at')
                ->where('id', $winnerId)
                ->first();

            return response()->json([
                'success' => true,
                'message' => '抽奖成功！',
                'data' => [
                    'winner' => [
                        'id' => $winner->id,
                        'nickname' => $winner->nickname ?? '未设置昵称',
                        'openid' => $winner->openid,
                        'created_at' => $winner->created_at->format('Y-m-d H:i:s') // 格式化注册时间
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            \Log::error('抽奖失败：' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '抽奖过程中出现错误'
            ], 500);
        }
    }

    /**
     * 显示参与者列表
     */
    public function participants(Lottery $lottery)
    {
        $participants = $lottery->participants()->paginate(15);
        return view('lottery.participants', compact('lottery', 'participants'));
    }

    /**
     * 显示中奖记录列表
     */
    public function winners()
    {
        // 使用原生SQL查询获取中奖记录
        $winners = \DB::table('lottery_results')
            ->select(
                'lottery_results.id',
                'lottery_results.wechat_users_id',
                'wechat_users.nickname',
                'lottery_results.draw_time',
                'verification_codes.card_number',
                'verification_codes.is_used'
            )
            ->leftJoin('wechat_users', 'lottery_results.wechat_users_id', '=', 'wechat_users.id')
            ->leftJoin('verification_codes', 'lottery_results.verification_codes_id', '=', 'verification_codes.id')
            ->orderBy('lottery_results.draw_time', 'desc')
            ->paginate(15);

        // 统计信息
        $totalWinners = \DB::table('lottery_results')->count();
        $boundCodes = \DB::table('lottery_results')
            ->join('verification_codes', 'lottery_results.verification_codes_id', '=', 'verification_codes.id')
            ->where('verification_codes.is_used', 3)
            ->count();

        return view('lottery.winners', compact('winners', 'totalWinners', 'boundCodes'));
    }

    /**
     * 保存抽奖结果
     */
    public function saveResult(Request $request)
    {
        try {
            $validated = $request->validate([
                'winner_id' => 'required|exists:wechat_users,id'
            ]);

            // 获取中奖用户信息
            $winner = \App\Models\WechatUser::find($validated['winner_id']);

            // 保存中奖记录，使用服务器时间
            \App\Models\LotteryResult::create([
                'wechat_users_id' => $winner->id,
                'verification_codes_id' => null,
                'draw_time' => now() // 使用服务器当前时间
            ]);

            return response()->json([
                'success' => true,
                'message' => '中奖结果保存成功！',
                'redirect' => route('admin.lottery.winners-list')
            ]);

        } catch (\Exception $e) {
            \Log::error('保存中奖结果失败：' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '保存结果时出现错误'
            ], 500);
        }
    }

    /**
     * 显示中奖清单
     */
    public function winnersList()
    {
        // 只从 lottery_results 表获取数据，不再依赖 lotteries 
        $winners = \App\Models\LotteryResult::with('wechatUser')
            ->latest('draw_time')
            ->paginate(15);

        return view('lottery.winners-list', compact('winners'));
    }

    /**
     * 绑定兑换码到用户
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function bindCode(Request $request)
    {
        try {
            // 验证请求数据
            $validated = $request->validate([
                'user_id' => 'required|exists:wechat_users,id',
                'card_number' => 'required|string|min:8|regex:/^\d+$/'
            ]);

            // 查找验证码
            $verificationCode = VerificationCode::where('card_number', $validated['card_number'])->first();

            if (!$verificationCode) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到该兑换码'
                ]);
            }

            // 检查验证码状态
            if ($verificationCode->is_used === 1) {
                return response()->json([
                    'success' => false,
                    'message' => '该兑换码已被使用'
                ]);
            }

            // 开始绑定流程
            DB::beginTransaction();
            try {
                // 更新验证码状态为已绑定(3)
                $verificationCode->update([
                    'is_used' => 3,
                    'wechat_user_id' => $validated['user_id']
                ]);

                // 创建抽奖结果记录
                LotteryResult::create([
                    'wechat_users_id' => $validated['user_id'],
                    'verification_codes_id' => $verificationCode->id,
                    'draw_time' => now()
                ]);

                DB::commit();

                return response()->json([
                    'success' => true,
                    'message' => '兑换码绑定成功'
                ]);

            } catch (\Exception $e) {
                DB::rollBack();
                throw $e;
            }

        } catch (\Exception $e) {
            Log::error('绑定兑换码失败', [
                'error' => $e->getMessage(),
                'user_id' => $request->input('user_id'),
                'card_number' => $request->input('card_number')
            ]);

            return response()->json([
                'success' => false,
                'message' => '绑定失败，请稍后重试'
            ]);
        }
    }

    /**
     * 查询兑换码
     */
    public function searchCode(Request $request)
    {
        try {
            $cardNumber = $request->query('code');
            
            if (!$cardNumber) {
                return response()->json([
                    'success' => false,
                    'message' => '请输入兑换码编号'
                ], 400);
            }

            // 使用 card_number 字段查询兑换码，并加载关联的商品信息
            $verificationCode = \App\Models\VerificationCode::with(['product', 'codeActivity'])
                ->where('card_number', $cardNumber)
                ->where('is_used', false)
                ->first();

            if (!$verificationCode) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到可用的兑换码'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $verificationCode->id,
                    'card_number' => $verificationCode->card_number,
                    'code' => $verificationCode->code,
                    'expired_at' => $verificationCode->expired_at ? $verificationCode->expired_at->format('Y-m-d H:i:s') : '永久有效',
                    'product' => [
                        'name' => $verificationCode->product->name ?? '未知商品',
                        'description' => $verificationCode->product->description ?? '',
                        'price' => $verificationCode->product->price ?? 0,
                        'value' => $verificationCode->value ?? 0
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            \Log::error('查询兑换码失败：' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '查询兑换码时出现错误'
            ], 500);
        }
    }
} 